<template>
  <div class="box-padding">
    <div class="page-container">
      <div class="left-panel">
        <el-form
          :model="formData"
          ref="formData"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row>
            <!-- 第一个表单项 -->
            <el-col :span="8">
              <el-form-item label="断面名称" prop="name">
                <el-input v-model="formData.dmmc" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="旗区名称">
                <el-input v-model="formData.xzqhname" readonly></el-input>
              </el-form-item>
            </el-col>
            <!-- 第二个表单项 -->
            <el-col :span="8">
              <el-form-item label="监测日期">
                <el-date-picker
                  v-model="formData.jcsj"
                  type="month"
                  placeholder="选择日期"
                  readonly
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!-- 第三个表单项 -->
            <el-col :span="8">
              <el-form-item label="监测报告上传" prop="filename">
                <el-upload
                  class="upload-demo"
                  action="http://49.232.236.127/stbj/rest/uploadMultipleFileNew"
                  :data="{ fileType: '' }"
                  :on-success="handleUploadSuccess"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                >
                  <el-button slot="trigger" size="medium" type="primary"
                    >点击上传</el-button
                  >
                </el-upload>
              </el-form-item>
            </el-col>
            <!-- 第四个表单项 -->
            <el-col :span="8">
              <el-form-item label="水质监测" class="water-quality-item">
                <el-button type="primary" size="medium">模板上传</el-button>
                <el-button type="primary" size="medium">模板下载</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="right-panel">
        <!-- 左侧表格 -->
        <div class="table-container">
          <el-table :data="leftTableData" style="width: 100%; height: 100%">
            <el-table-column prop="label" label="监测因子"></el-table-column>
            <el-table-column prop="category" label="测定值">
              <template slot-scope="scope">
                <el-input
                  type="number"
                  v-model="formData[scope.row.value]"
                  @input="calculateCategory(scope.row)"
                >
                  <span slot="suffix" class="custom-suffix">{{
                    scope.row.units
                  }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="类别"></el-table-column>
          </el-table>
        </div>

        <!-- 右侧表格 -->
        <div class="table-container">
          <el-table :data="rightTableData" style="width: 100%; height: 100%">
            <el-table-column prop="label" label="监测因子"></el-table-column>
            <el-table-column prop="category" label="测定值">
              <template slot-scope="scope">
                <el-input
                  type="number"
                  v-model="formData[scope.row.value]"
                  @input="calculateCategory(scope.row)"
                >
                  <span slot="suffix" class="custom-suffix">{{
                    scope.row.units
                  }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="类别"></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div class="bottom-actions">
      <el-button @click="goBack" size="medium">返回</el-button>
      <el-button
        v-if="!isViewPage"
        type="primary"
        @click="submitForm('formData')"
        size="medium"
        >保存</el-button
      >
      <el-button
        v-if="!isViewPage"
        type="success"
        @click="handleSubmit"
        size="medium"
        >提交</el-button
      >
      <!-- <el-button @click="resetForm('formData')">重置</el-button> -->
    </div>
  </div>
</template>

<script>
import { MessageBox } from "element-ui";
export default {
  data() {
    return {
      isEditable: true, // 是否可编辑旗区名称
      isViewPage: false, // 是否为查看页面，默认为否
      fileList: [],
      formData: {
        id: null,
        szlb: null,
        jcsj: null,
        xzqhdm: null,
        dmmc: null,
        sw: null,
        swfl: null,
        ph: null,
        phfl: null,
        rjy: null,
        gmsyzs: null,
        cod: null,
        bod5: null,
        nh3n: null,
        zl: null,
        zd: null,
        tong: null,
        xin: null,
        meng: null,
        fhw: null,
        xi: null,
        shen: null,
        gong: null,
        ge: null,
        luo: null,
        qian: null,
        qhw: null,
        hff: null,
        syl: null,
        ylzbmhxj: null,
        lhw: null,
        fdcjq: null,
        zl1: null,
        shenhezt: null,
        filename: null,
        url: null,
        jianceshujulx: null,
        createtime: null,
        updatetime: null,
      },
      xzqhOptions: [
        { xzqhname: "东胜区", xzqhcode: "150602" },
        { xzqhname: "康巴什区", xzqhcode: "150603" },
        { xzqhname: "达拉特旗", xzqhcode: "150621" },
        { xzqhname: "准格尔旗", xzqhcode: "150622" },
        { xzqhname: "鄂托克前旗", xzqhcode: "150623" },
        { xzqhname: "鄂托克旗", xzqhcode: "150624" },
        { xzqhname: "杭锦旗", xzqhcode: "150625" },
        { xzqhname: "乌审旗", xzqhcode: "150626" },
        { xzqhname: "伊金霍洛旗", xzqhcode: "150627" },
      ],

      jcjgArray: [
        {
          value: "rjy",
          label: "溶解氧",
          lb1: 7.5,
          lb2: 6,
          lb3: 5,
          lb4: 3,
          lb5: 2,
          fh: ">=",
          units: "mg/L",
        },
        {
          value: "gmsyzs",
          label: "高猛酸盐指数",
          lb1: 2,
          lb2: 4,
          lb3: 6,
          lb4: 10,
          lb5: 15,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "tong",
          label: "铜",
          lb1: 0.01,
          lb2: 1,
          lb3: 1,
          lb4: 1,
          lb5: 1,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "xin",
          label: "锌",
          lb1: 0.05,
          lb2: 1,
          lb3: 1,
          lb4: 2,
          lb5: 2,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "qian",
          label: "铅",
          lb1: 0.01,
          lb2: 0.01,
          lb3: 0.05,
          lb4: 0.05,
          lb5: 0.1,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "ge",
          label: "镉",
          lb1: 0.001,
          lb2: 0.005,
          lb3: 0.005,
          lb4: 0.005,
          lb5: 0.01,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "hff",
          label: "挥发酚",
          lb1: 0.002,
          lb2: 0.002,
          lb3: 0.005,
          lb4: 0.01,
          lb5: 0.1,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "zl",
          label: "总磷（河流）",
          lb1: 0.02,
          lb2: 0.1,
          lb3: 0.2,
          lb4: 0.3,
          lb5: 0.4,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "ylzbmhxj",
          label: "阴离子表面活性剂",
          lb1: 0.2,
          lb2: 0.2,
          lb3: 0.2,
          lb4: 0.3,
          lb5: 0.3,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "cod",
          label: "化学需氧量",
          lb1: 15,
          lb2: 15,
          lb3: 20,
          lb4: 30,
          lb5: 40,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "nh3n",
          label: "氨氮",
          lb1: 0.15,
          lb2: 0.5,
          lb3: 1,
          lb4: 1.5,
          lb5: 2,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "zd",
          label: "总氮",
          lb1: 0.2,
          lb2: 0.5,
          lb3: 1,
          lb4: 1.5,
          lb5: 2,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "qhw",
          label: "氰化物",
          lb1: 0.005,
          lb2: 0.05,
          lb3: 0.2,
          lb4: 0.2,
          lb5: 0.2,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "luo",
          label: "铬（六价）",
          lb1: 0.01,
          lb2: 0.05,
          lb3: 0.05,
          lb4: 0.05,
          lb5: 0.1,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "shen",
          label: "砷",
          lb1: 0.05,
          lb2: 0.05,
          lb3: 0.05,
          lb4: 0.1,
          lb5: 0.1,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "xi",
          label: "硒",
          lb1: 0.01,
          lb2: 0.01,
          lb3: 0.01,
          lb4: 0.02,
          lb5: 0.02,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "gong",
          label: "汞",
          lb1: 0.00005,
          lb2: 0.00005,
          lb3: 0.0001,
          lb4: 0.001,
          lb5: 0.001,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "lhw",
          label: "硫化物",
          lb1: 0.05,
          lb2: 0.1,
          lb3: 0.5,
          lb4: 0.5,
          lb5: 1,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "bod5",
          label: "生化需氧量",
          lb1: 3,
          lb2: 3,
          lb3: 4,
          lb4: 6,
          lb5: 10,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "fhw",
          label: "氟化物",
          lb1: 1,
          lb2: 1,
          lb3: 1,
          lb4: 1.5,
          lb5: 1.5,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "fdcjq",
          label: "粪大肠菌群",
          lb1: 200,
          lb2: 2000,
          lb3: 10000,
          lb4: 20000,
          lb5: 40000,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "syl",
          label: "石油类",
          lb1: 0.05,
          lb2: 0.05,
          lb3: 0.05,
          lb4: 0.5,
          lb5: 0.1,
          fh: "<=",
          units: "mg/L",
          // },{
          //     value: 23,
          //     label: '电导率'
          // },{
          //     value: 'sw',
          //     label: '水温'
          // },{
          // value: 'swfl',
          // label: '水温分类'
          // },{
          //     value: 'phfl',
          //     label: 'pH分类'
        },

        // {
        //   value: "swfl",
        //   label: "水温分类",
        // },
        // {
        //   value: "phfl",
        //   label: "pH分类",
        // },
        {
          value: "zl1",
          label: "总磷（湖，库）",
          lb1: 0.01,
          lb2: 0.025,
          lb3: 0.05,
          lb4: 0.1,
          lb5: 0.2,
          fh: "<=",
          units: "mg/L",
        },
        {
          value: "sw",
          label: "水温",
          units: "℃",
        },
        {
          value: "ph",
          label: "PH值",
          units: "",
        },
      ],
      leftTableData: [],
      rightTableData: [],
    };
  },
  mounted() {
  
    this.splitTableData();
    console.log(this.$route);
    this.formData.dmmc = this.$route.params.dmmc;
    this.formData.jcsj = new Date(this.$route.params.jcsj);
    this.formData.xzqhname = this.$route.params.xzqhname;
    this.formData.xzqhcode = this.$route.params.xzqhcode;
  },
  created() {
    this.fetchData();
    console.log('路由',this.$route.params);
    if (!this.$route.params.dmmc) {
      this.goBack();
    }
    console.log("拿到的id", this.$route.params.id);
    console.log("拿到的断面名称", this.$route.params.dmmc);
    if (this.$route.params.shenhezt === "00") {
      console.log("录入页面", this.$route.params.shenhezt);
      this.isViewPage = false;
       // 不是查看页面
    } else if (
      this.$route.params.shenhezt === "01" ||
      this.$route.params.shenhezt === "04"
    ) {
      console.log("修改页面", this.$route.params.shenhezt);
      this.isViewPage = false; // 不是查看页面
      this.fetchDataById(this.$route.params.id);

      console.log("文件", this.fileList);
      // 根据id调用接口拿到数据
    } else {
      console.log("查看页面", this.$route.params.shenhezt);
      this.isViewPage = true; // 是查看页面
      this.fetchDataById(this.$route.params.id);
    }
  },
  methods: {
    calculateCategories() {
      // 遍历左侧表格数据
      this.leftTableData.forEach((item) => {
        this.calculateCategory(item);
      });

      // 遍历右侧表格数据
      this.rightTableData.forEach((item) => {
        this.calculateCategory(item);
      });
    },
    fetchData() {
      // 调用 user.js 中的 getData 方法
      // console.log("登录信息", this.$store.state);

      this.$api
        .getUser()
        .then((response) => {
          if (response.data.code == 906) {
            // return  alert('token已过期')
            this.$router.push(`/login`);
          }

          console.log("数据1", response);
          const userAreaCode = response.data.data.areacode; // 示例用户区域编码
          if (userAreaCode === "1506") {
            // 管理员用户
            this.isEditable = true;
          } else {
            // 非管理员用户
            this.isEditable = false;
            // 根据用户区域编码设置旗区名称
            this.setAreaCode(userAreaCode);
          }
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },
    // 根据ID调用接口获取数据
    fetchDataById(id) {
      if (!id) {
        return;
      }
      this.$api
        .getNDmSzjcDataById(id)
        .then((response) => {
          console.log("根据id拿到的数据", response);
          // 根据接口返回的数据设置输入框的默认值
          this.formData = response.data.data; // 假设接口返回的数据直接包含表单数据，根据实际情况进行调整
          this.formData.xzqhname = this.$route.params.xzqhname;
          // 计算类别并赋值给每一行监测因子的对象
          this.calculateCategories();
          this.showUploadedFiles();
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
        });
    },
    handleChange(value) {
      // 根据选择的行政区划代码更新行政区划名字
      const selectedOption = this.xzqhOptions.find(
        (option) => option.xzqhcode === value
      );
      this.formData.xzqhdm = selectedOption ? selectedOption.xzqhcode : null;
    },
    submitForm() {
      // 将所有测定值对应的类别字符串转换为数字并进行比较
      let maxCategory = "Ⅰ类"; // 默认最大类别为Ⅰ类
      let maxCategoryNumber = 1;

      // 遍历所有测定值的类别字符串，找到最大的类别
      this.leftTableData.forEach((item) => {
        const categoryNumber = this.categoryToNumber(item.category);
        if (categoryNumber > maxCategoryNumber) {
          maxCategoryNumber = categoryNumber;
          maxCategory = item.category;
        }
      });

      this.rightTableData.forEach((item) => {
        const categoryNumber = this.categoryToNumber(item.category);
        if (categoryNumber > maxCategoryNumber) {
          maxCategoryNumber = categoryNumber;
          maxCategory = item.category;
        }
      });
      this.formData.szlb = maxCategoryNumber;
      MessageBox.confirm(
        `您所选的水质类别为：${maxCategory}，是否确认提交？`,
        "确认提交",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 提交表单的逻辑
          console.log("提交的表单数据:", this.formData);
          // 用户点击了确定按钮，执行提交操作
          if (this.$route.params.shenhezt === "00") {
            this.formData.shenhezt = "01";
            this.addData(this.formData);
          } else if (
            this.$route.params.shenhezt === "01" ||
            this.$route.params.shenhezt === "04"
          ) {
            this.xiugai(this.formData);
            this.formData.shenhezt = "01";
          }
        })
        .catch(() => {
          // 用户点击了取消按钮，不执行提交操作
        });
    },
    categoryToNumber(category) {
      switch (category) {
        case "Ⅰ类":
          return 1;
        case "Ⅱ类":
          return 2;
        case "Ⅲ类":
          return 3;
        case "Ⅳ类":
          return 4;
        case "Ⅴ类":
          return 5;
        case "劣Ⅴ类":
          return 6;
        default:
          return 0; // 无分类
      }
    },

    addData(data) {
      this.$api.addNDmSzjcData(data).then((response) => {
        console.log(response);
        this.$message.success("录入成功");
        this.goBack();
      });
    },
    xiugai(data) {
      this.$api.editNDmSzjcData(data).then((response) => {
        console.log(response);
        this.$message.success("修改成功");
        this.goBack();
      });
    },
    handleUploadSuccess(response, file, fileList) {
      console.log("上传成功", response.data[0].newFileName);
      console.log(typeof response.data);
      if (!this.formData.filename) {
        this.formData.filename = response.data[0].newFileName;
      } else {
        this.formData.filename += "," + response.data[0].newFileName;
      }
      this.fileList = fileList;
      console.log("111", this.fileList);
    },
    handleRemove(file, fileList) {
      const index = fileList.findIndex((item) => item.name === file.name);
      if (index !== -1) {
        fileList.splice(index, 1); // 从文件列表中移除被删除的文件
      }

      // 从 formData.filename  中移除被删除的文件名
      const filenames = this.formData.filename.split(",");

      const filenameIndex = filenames.findIndex((item) => item === file.name);

      if (filenameIndex !== -1) {
        filenames.splice(filenameIndex, 1);
        this.formData.filename = filenames.join(",");
      }
    },
    showUploadedFiles() {
      console.log("进来了");
      // 如果 formData 中存在已上传的文件名
      console.log("22", this.formData.filename);
      if (this.formData.filename) {
        console.log("又进来了");
        // 拆分文件名字符串，使用逗号作为分隔符
        const filenames = this.formData.filename.split(",");
        console.log("filenames", filenames);
        // 遍历每个文件名，构建完整的文件地址，并将地址放入 fileList 中
        filenames.forEach((filename) => {
          if (filename.trim() !== "") {
            const fileUrl = "http://49.232.236.127/stbjfile/" + filename;
            console.log("文件地址", fileUrl);

            this.fileList.push({
              name: filename,
              url: fileUrl,
            });
          }
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    calculateCategory(row) {
      const value = this.formData[row.value];
      // console.log("row", row);
      if (!value) {
        this.$set(row, "category", "");
        return;
      } // 如果输入为空，则不计算类别
      // const value = parseFloat(row.value);

      // console.log('=====', value);

      // 用户输入的值
      const labels = ["Ⅰ类", "Ⅱ类", "Ⅲ类", "Ⅳ类", "Ⅴ类"]; // 水质类别标签
      const lb = [row.lb1, row.lb2, row.lb3, row.lb4, row.lb5]; // 获取当前监测因子对象的 lb1 到 lb5
      const fh = row.fh; // 获取比较符号
      // console.log("VALUE1111", value);
      for (let j = 0; j < lb.length; j++) {
        // console.log("VALUE", value);
        if (
          (fh === ">=" && value >= lb[j]) ||
          (fh === "<=" && value <= lb[j])
        ) {
          // 如果用户输入的值满足某个标准值，设置对应的水质类别并结束循环
          this.$set(row, "category", labels[j]);

          return;
        }
      }
      // 如果用户输入的值小于所有标准值，设置为劣Ⅴ类
      this.$set(row, "category", "劣Ⅴ类");
    },
    splitTableData() {
      this.jcjgArray.forEach((item, index) => {
        if (index % 2 === 0) {
          // 如果是偶数项，添加到右侧表格数据
          this.leftTableData.push({ ...item, category: null });
        } else {
          // 如果是基数项，添加到左侧表格数据

          this.rightTableData.push({ ...item, category: null });
        }
      });
    },
    setAreaCode(userAreaCode) {
      console.log("打印当前行政区划", this.formData.xzqhdm);
      switch (userAreaCode) {
        case "150601":
          this.formData.xzqhdm = "150601";
          break;
        case "150602":
          this.formData.xzqhdm = "150602";
          break;
        case "150621":
          this.formData.xzqhdm = "150621";
          break;
        case "150622":
          this.formData.xzqhdm = "150622";
          break;
        case "150623":
          this.formData.xzqhdm = "150623";
          break;
        case "150624":
          this.formData.xzqhdm = "150624";
          break;
        case "150625":
          this.formData.xzqhdm = "150625";
          break;
        case "150626":
          this.formData.xzqhdm = "150626";
          break;
        case "150627":
          this.formData.xzqhdm = "150627";
          break;
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    handleSubmit() {
      // 提交表单的逻辑
      // 弹出确认对话框
      if (!this.formData.id) {
        this.$message.warning("请先保存！");
        return; // 停止执行提交操作
      }
      this.$confirm("确定要提交吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮，调用提交接口

          this.$api
            .batshenheNDmSzjcData(this.formData.id, "02") // 假设调用的接口名为 oneKeyAudit
            .then((response) => {
              // 处理一键审核成功的逻辑
              console.log("单个提交返回的数据", response);
              this.$message.success("提交成功");
              this.goBack();
              // this.getUser(); // 刷新数据
            })
            .catch((error) => {
              // 处理一键审核失败的逻辑
              console.error("提交失败", error);
              this.$message.error("提交失败");
            });
        })
        .catch(() => {
          // 用户点击了取消按钮，不执行任何操作
        });
    },
  },
};
</script>

<style>
.app-main {
  height: auto !important; /* 设置高度为自动以允许内容撑开 */
}
.box-padding {
  padding-bottom: 80px;
}

.page-container {
  /* display: flex; */
}

.left-panel {
  flex: 1;
  padding: 20px;
  border-right: 1px solid #eee;
  overflow-y: auto; /* 左侧内容超出时显示滚动条 */
}

/* .right-panel {
  flex: 2;
  padding: 20px;

  overflow-y: auto;
} */
.right-panel {
  display: flex;
  padding: 20px;
  flex-direction: row;
}

.table-container {
  flex: 1; /* 自动填充剩余空间 */
  margin-right: 20px; /* 添加一些间距 */
}

.table-container:last-child {
  margin-right: 0; /* 最后一个表格容器不需要右边距 */
}

.table-container {
  /* overflow-y: auto;  */
  height: 100%;
}

.bottom-actions {
  /* position: fixed;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%); */
  /* text-align: center; */
  /* margin-top: 20px; */
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  padding: 20px 0 40px 0;
  background-color: #fff; /* 使按钮背景色为白色以覆盖可能存在的内容 */
}

.custom-suffix {
  line-height: 36px; /* 与 el-input 的高度相同 */
}

/* 隐藏输入框的上下箭头 */
input[type="number"] {
  -moz-appearance: textfield; /* Firefox */
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0; /* 可以根据需要调整 */
}
</style>
